const {exec} = require('child_process');
const path = require('path');
const pjson = require('./package.json');
let root
if (process.pkg) {
    // 如果是 pkg 打包后的执行文件
    root = path.dirname(process.execPath); // 使用 process.execPath 获取可执行文件路径
} else {
    // 开发模式
    root = __dirname;
}

function askDialog(config) {
    let filename;
    let cmd = path.join('python', 'dist');
    if (process.platform === 'linux') {
        filename = 'node-file-dialog';
        if (process.arch === 'x86') filename += '-xi686.AppImage'
        else filename += '-x86_64.AppImage'
        cmd = path.join(cmd, 'linux', filename)
    }
    if (process.platform === 'win32') {
        filename = 'dialog';
        if (process.arch === 'x86') filename += '-x86'
        cmd = path.join(cmd, 'windows', filename + '.exe')
    }
    if (config.type === 'directory')
        cmd += ' -d';
    else if (config.type === 'save-file')
        cmd += ' -s';
    else if (config.type === 'open-file')
        cmd += ' -o';
    else if (config.type === 'open-files')
        cmd += ' -f';
    return new Promise((resolve, reject) => {
        console.log(root, cmd)
        exec(path.join(root, cmd), (error, stdout, stderr) => {
            if (stdout) {
                if (stdout.trim() === 'None')
                    reject(new Error('Nothing selected'));
                else
                    resolve(stdout.trim().split('\n'))
            } else if (error) {
                reject(new Error(error));
            } else if (stderr) {
                reject(new Error(stderr));
            }
        });
    });
}

module.exports = askDialog;
